function Cap = FindCapRate_GHQ(D_type,D_level,P_u,P_d,r,tau,fee,c_bar,R_S_RN,weight)

% Find break-even cap rate: --> discounted expected payout of RILA should equal cost 'c_bar'  
options = optimset('Display','none');
if (P_u == 0) && (P_d == 0) % if both part. rates are 0, then there is no equity exposure, thus no "fair" cap rate can be found (i.e., there should be no cap).
    Cap = 100;
else
    [Cap,~,exitflag] = fsolve(@(C) ExpLoss(D_type,D_level,P_u,P_d,C,r,tau,fee,c_bar,R_S_RN,weight) , 0.1 , options);
    if exitflag < 0 % 'fsolve' didn't find a solution (--> this is b/c there is no cap rate that solves the pricing equation).
        if ExpLoss(D_type,D_level,P_u,P_d,100,r,tau,fee,c_bar,R_S_RN,weight) > 0
            Cap = 100;
        else
            Cap = 0;
        end
    end
end
return
end


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function EL = ExpLoss(D_type,D_level,P_u,P_d,Cap,r,tau,fee,c_bar,R_S,weight)

A_t = 1000;
if D_type == "Buffer"
    B = D_level;
    R_A = min(P_d*R_S+B , 0) .* (R_S<0) + min(P_u*R_S,Cap) .* (R_S>0);     % vector (N_sim-by-1) of credited return to RILA account.
elseif D_type == "Floor"
    F = D_level;
    R_A = max(P_d*R_S , -F) .* (R_S<0) + min(P_u*R_S,Cap) .* (R_S>0);     % vector (N_sim-by-1) of credited return to RILA account.
else
    disp('Error. Downside protection type unspecified.')
    asdfadsf    % to produce error
end

A_tplustau = A_t * exp(-fee*tau) * (1+R_A);
L = A_tplustau * exp(-r*tau) + A_t * c_bar * tau - A_t;
EL = weight' * L;
return
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%